import os
import random

import click
from apps import create_app
from apps.blueprints.article.models import Articles
from apps.blueprints.goods.models import Goods, User_Goods
from apps.blueprints.user.models import User
from exts import db
from faker import Faker
from flask.cli import with_appcontext
from flask_migrate import Migrate

# from flask_script import Manager

app = create_app()

@click.group()
def cli():
    # flask应用管理命令行工具
    pass

@cli.command()
@click.option('--host', default='127.0.0.1', help='The host to run the server on')
@click.option('--port', default=5000, help='The port to run the server on')
def run(host, port):
    app.run(host=host, port=port)
# 命令工具
@cli.command()
@with_appcontext
def initdb():
    db.create_all()
    print('初始化数据库成功')   

@cli.command()
@with_appcontext
def dropdb():
    db.drop_all()
    print('删除数据库成功')

@cli.command()
@with_appcontext
def deldb():
    db_path = app.config['SQLALCHEMY_DATABASE_URI'].split('///')[1]
    if os.path.exists(db_path):
        os.remove(db_path)
        print('数据库文件已删除')
    else:
        print('数据库文件不存在')
        
@cli.command()
@with_appcontext
def adduser():
    faker= Faker(locale='zh_CN')
    # print(faker.name())
    for index in range(1, 200):
        user = User(username=f'{faker.name()}{index}', password=f"123{random.randint(10, 99)}",
                        phone=f"158{random.randint(10000000, 99999999)}")
        db.session.add(user)
        db.session.commit()
        print(f'user:{user} 添加成功')

@cli.command()
@with_appcontext
def addarticle():
    faker= Faker(locale='zh_CN')
    users = User.query.all()
    for user in users:
        # print(user.id)
        
        article = Articles(title=f'{faker.name()}{user.id}', 
                           content=f"测试博客{random.randint(1000, 999999)}",
                           user_id=user.id,
                           type_id=random.randint(1, 10)
                           )
        db.session.add(article)
        db.session.commit()
        print(f'article:{article} 添加成功')
 

@cli.command()
@with_appcontext
def addgoods():
    faker= Faker(locale='zh_CN')
    goodsname = ['手机','电脑','平板','电视','洗衣机','空调','冰箱','热水器','音响']
    goodsname += ['键盘',"内衣",'衣服','裤子','帽子','袜子','鞋子','汽车','自行车','火车']
    for index in range(1, 200):
        # print(f'{}')
        name = f'{goodsname[random.randint(0,len(goodsname)-1)]}{index}'
        # print(name)
        goods = Goods(gname=name, 
                     price=random.randint(100, 9999)/10.0)
    
        db.session.add(goods)
        db.session.commit()
        print(f'添加< {goods} >商品成功!')
  


              
if __name__ == '__main__':
    cli()